package com.cs.dingdingauto;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.util.Log;

import java.util.List;

/**
 * @author liguandong
 * @data 2023/7/5
 */
public class AppUtils {
    /**
     * 判断应用软件是否运行在前台
     *
     * @param context
     * @param packageName 应用软件的包名
     * @return
     */
    public static boolean isTopActivity(Context context, String packageName) {
        return isTopActivity(context, packageName, null);
    }

    /**
     * 判断某一Activity是否运行在前台
     *
     * @param context
     * @param packageName 应用软件的包名
     * @return
     */
    public static boolean isTopActivity(Context context, String packageName, String className) {
        try {
            ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
            if (tasksInfo.size() > 0) {
                // Activity位于堆栈的顶层,如果Activity的类为空则判断的是当前应用是否在前台
                if (packageName.equals(tasksInfo.get(0).topActivity.getPackageName())
                              && (className == null || className.equals(tasksInfo.get(0).topActivity.getClassName()))) {
                    return true;
                }
            }
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isAppForeground(Context context) {
        ActivityManager activityManager =
                      (ActivityManager)context.getSystemService(Service.ACTIVITY_SERVICE);
        //获取app运行中的process集合
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList =
                      activityManager.getRunningAppProcesses();
        if (runningAppProcessInfoList == null) {
            return false;
        }
        //processInfo.processName是进程名
        for(ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList) {
            //判断进程的重要级别和进程名与包名的比较
            //ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND=100
            //importance属性==100 表示这个进程在前台，其他数字表示在后台，所以通过importance和processName判断应用是否在前台
            if (processInfo.processName.equals(context.getPackageName())
                          &&(processInfo.importance ==
                          ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)) {
                return true;
            }
        }
        return false;
    }
}
